<?php

namespace common\components;

use Closure;
use common\widgets\grid\BulkAjaxActionBtn;
use common\widgets\pages\AdminPage;
use common\widgets\pages\FormViewPage;
use common\widgets\pages\GridViewPage;
use Yii;
use yii\helpers\ArrayHelper;
use yii\web\HttpException;

/**
 * 基础控制器组件
 *
 * @package common\components
 */
class AdminController extends WebController
{

    /**
     * {@inheritdoc}
     */
    public $enableCsrfValidation = false;

    /**
     * {@inheritdoc}
     */
    public $rootActions = [];

    /**
     * 批量操作按钮
     *
     * @param Closure $handler
     * @return string
     * @throws \yii\web\HttpException
     */
    public function ajaxBulkAction(Closure $handler)
    {
        if (Yii::$app->getRequest()->validateCsrfToken() && Yii::$app->getRequest()->isAjax)
        {
            if (($ids = Yii::$app->request->post('keys')) !== null)
            {
                $result = $handler($ids);
                if (is_array($result))
                {
                    return BulkAjaxActionBtn::ajaxReturnSuccess($result['msg'], $result['code'], $result['data']);
                }
                else
                {
                    return BulkAjaxActionBtn::ajaxReturnSuccess($result);
                }
            }
            else
            {
                throw new HttpException(400, "Illegal request.");
            }
        }
        else
        {
            return BulkAjaxActionBtn::ajaxReturnError("Illegal request or data.");
        }
    }

    /**
     * @param string $className
     * @param array  $params
     * @return  AdminPage
     */
    public function createPageInstance($className, $params = [])
    {
        if ( ! isset($params[AdminPage::CONTROLLER]))
        {
            $params[AdminPage::CONTROLLER] = $this;
        }

        return new $className($params);
    }

    /**
     * @param       $provider
     * @param       $searchModel
     * @param array $params
     * @return \common\widgets\pages\GridViewPage
     */
    public function createGridViewPage($provider, $searchModel, $params = [])
    {
        $params = ArrayHelper::merge([
            GridViewPage::DATA_PROVIDER => $provider,
            GridViewPage::SEARCH_MODEL  => $searchModel,
        ], $params);

        return $this->createPageInstance(GridViewPage::className(), $params);
    }

    /**
     * @param       $formModel
     * @param       $method
     * @param array $params
     * @return \common\widgets\pages\GridViewPage
     */
    public function createFormViewPage($formModel, $method, $params = [])
    {
        $params = ArrayHelper::merge([
            'formModel' => $formModel,
            'method'    => $method,
        ], $params);

        return $this->createPageInstance(FormViewPage::className(), $params);
    }
}
